# _*_ coding: utf-8 _*_
"""
    串口读取GPS数据和程序解析GPS数据，双线程并行执行
"""
import threading
import time
import queue
import serial

import gps



class MyThread(threading.Thread):
    def __init__(self, func, args, name=''):
        threading.Thread.__init__(self)
        self.name = name
        self.func = func
        self.args = args
        pass

    def run(self):
        self.func(*self.args)
    pass


def comRead():
    comThread = serial.Serial(
        port='com5', baudrate=115200,
        timeout=2
    )
    if comThread.isOpen() is not True:
        comThread.open()
    if comThread.isOpen():
        print(comThread.port)
        data = ''
        data = data.encode('utf-8')
        while True:
            time.sleep(0.01)
            n = comThread.inWaiting()
            if n:
                data += comThread.read(n)
                # print(type(data))

            n = comThread.inWaiting()
            if len(data) > 0 and n == 0:
                try:
                    print(data.decode('utf-8'))
                    # 清除缓存空间的数据
                    data = ''
                    data = data.encode('utf-8')
                except:
                    # print(data, len(data))
                    gpsbuffer = gps.GpsData
                    gps.MPU_analysis(gpsbuffer, data)
                    # 清除缓存空间的数据
                    data = ''
                    data = data.encode('utf-8')
                    # print("data error, try again\n")
                    # break

        comThread.close()
    pass


if __name__ == '__main__':
   comRead()